(function(){
	$('#create-poll').live('pageinit', function(event){
		//Create.init();
		$('#radio-login-required input:radio').change(checkLoginRequired).trigger("change");
		$('#radio-daily-period input:radio').change(checkDailyPeriod).trigger("change");
		$('#radio-limit input:radio').change(checkLimit).trigger('change');
		$('#text-location').keyup(setLocationSearch);
		$("#location-list").focus(function(){$(this).blur();});
	});
	
	function setLocationSearch(){
		if( $.locationSearchTimer)
			clearInterval($.locationSearchTimer);
		$.locationSearchTimer = setTimeout(searchLocation, 500);
	}
	
	function searchLocation(){
		var $this = $('#text-location'),
			val = $this.val();
			
		if(val.length < 2){
			$("#location-list").val('').fadeOut();
			$(".location-fields").fadeOut();
			return;
		}
			
		$.ajax({
			type : 'post',
			url : CI_ROOT + 'ajax/search_location_by_str',
			data : {
				text : val
			},
			success : function(res){
				var text = '';
				if(res.status && res.status == 'ok' ){
					if(res.data.count > 0){
						for(var i in res.data.locations){
							text += res.data.locations[i].address_str + (i == res.data.locations.length - 1 ? "" : "\n");
						}
						
						if(res.data.count > 5)
							text += "\n (총 "+res.data.count+"개가 검색됨)";
					}else{
						text = '검색 결과가 없습니다';
						$("#location-list").height(30);
					}
					
					$("#location-list").val(text).fadeIn().trigger('keyup');
					$(".location-fields").fadeIn();
				}
			},
			complete : function(){
				
			}
		});
	}
	
	function checkLimit(){
		var $field = $("#max-people-container");
		if($('#radio-limit input:radio:checked').val() == '0'){
			$field.hide();
			$field.find('input, select, textarea').attr({disabled: true});
		}else{
			$field.find('input, select, textarea').removeAttr('disabled');
			$field.show();
		}
	}
	
	function checkLoginRequired(){
		var $loginRequiredFields = $('.login-required-field').not("[id$='-template']");
		if($('#radio-login-required input:radio:checked').val() == '0'){
			$loginRequiredFields.hide();
			$loginRequiredFields.find('input, select, textarea').attr({disabled: true});
		}else{
			$loginRequiredFields.find('input, select, textarea').removeAttr('disabled');
			$loginRequiredFields.show();
		}
	}
	
	function checkDailyPeriod(){
		var $dailyPeriodField = $("#list-daily-period");
		if($('#radio-daily-period input:radio:checked').val() == 'once'){
			$dailyPeriodField.hide();
			$dailyPeriodField.find('input, select, textarea').attr({disabled: true});
		}else{
			$dailyPeriodField.find('input, select, textarea').removeAttr('disabled');
			$dailyPeriodField.show();
		}
	}
	
	/**
	 * 참여 조건 추가 팝업
	 */
	$('#page-add-condition').live('pageinit', function(e){
		var $page = $(this);
		$page.find('.address-selector').addressSelector();
		
		// 확인버튼 누르면 조건 추가하고 창 닫음
		$("#add-condition-button").click(addPollCondition);
		
		// 체크박스 내용에 따라 아래 필드 열고 닫음
		$page.find('input:checkbox[name="condition[]"]').change(function(){
			var $this = $(this);
			var $fieldContainer = $page.find('#condition-' + $this.val());
			var $fieldElems = $fieldContainer.find('input, select, textarea');
			if($this.is(":checked")){
				$fieldElems.removeAttr('disabled');
				if($fieldElems.is(":checkbox, :radio"))
					$fieldElems.checkboxradio("refresh");
				else if($fieldElems.is("select"))
					$fieldElems.selectmenu("refresh");
				$fieldContainer.show();
			}else{
				$fieldElems.attr('disabled', 'true');
				$fieldContainer.hide();
			}
		})
	}).live('pagebeforeshow', function(e){
		// 창 열리기 전 초기화
		var $page = $(this);
		$page
			.find("form").each(function(){
				this.reset();
			})
			.find('input:checkbox, input:radio').checkboxradio('refresh').end()
			.find('select').selectmenu("refresh").end()
			.find('li[id^=condition]')
				.find("input, select, textarea").attr("disabled", "true").end()
				.hide();
	});
	
	function addPollCondition(){
		var $page = $('#page-add-condition');
		var $checked = $page.find('input[name="condition[]"]:checked');
		var html = '';

		/**
		 * 선택된 값들 추출
		 */
		$checked.each(function(idx){
			var $this = $(this);
			var $field = $page.find("#condition-"+$this.val());
			var label = "" + $("label[for='"+$this.prop("id")+"']").text();
			
			var text = "";
				
			switch($this.prop("id").replace("check-condition-", "")){
				case "address":
					$field.find("select").each(function(){
						var $this = $(this);
						var val = $this.val(); 
						if(val != "")
							text += $this.find("option[value='"+val+"']").text() + " ";
					});
					break;
				case "gender":
					text = $field.find("label[for='" + $field.find("input:checked").prop("id") + "']").text();
					break;
				case "age-range":
				case "education":
					var val = $field.find("select").val();
					if(val != "")
						text = $field.find("option[value='"+ val  +"']").text();
					break;
				default:
			}
			
			if(text == ""){
				$this.removeAttr("checked").trigger("change").checkboxradio("refresh");
			}else{
				html += "<p>" + label + ": " + text + "</p>";
			}
		});
		
		// 실제로 값이 입력된 필드만 다시 추출
		$checked = $page.find('input[name="condition[]"]:checked');
		if( $checked.length == 0 ){
			alert('조건을 입력해 주십시오');
			return false;	
		}
		
		var value = $page.find("form").serialize();
		if( $(".list-condition-rule input:hidden[value='"+value+"']").length > 0 ){
			alert('동일한 조건이 존재합니다.');
			return false;
		}
		
		// 원래 폼에 조건 필드 추가
		var $li = $('#list-condition-template').clone()
					.removeAttr('id')
					.find('.condition-text').html(html).end()
					.find('input[name="condition_rules[]"]').removeAttr("disabled").val(value).end()
					.find(".condition-delete-button").click(function(){
						$(this).parent('.list-condition-rule')
							.fadeOut(function(){ $(this).remove(); });
					}).end()
					.insertAfter(".list-condition-rule:last").show();
		$page.dialog('close');
	}
	
	/**
	 * 문항 추가 팝업
	 */
	$("#page-add-question").live("pageinit", function(){
		var $page = $(this);
		$page.find("#select-question-type").change(setQuestionType);
		$page.find("#button-add-option").click(addQuestionOption);
		$page.find("#add-question-button").click(addQuestion);
		
	}).live("pagebeforeshow", function(){
		var $page = $(this);
		$page.find("input:text").val('');
		$page.find("#select-question-type").trigger("change");
	});
	
	function setQuestionType(){
		var $page = $("#page-add-question");
		var $this = $("#select-question-type");
		var val = $this.val();
		var $divider = $page.find("#option-divider");
		var $addButtonContainer = $page.find("#list-add-option");
		var $oldOptions = $divider.nextAll(".list-question-option");
		var numOptions = 0;
		
		if(val == "select"){
			numOptions = Math.max($oldOptions.length, 5);
			for(var i = $oldOptions.length; i <= 5; i++){
				$.createQuestionOption().insertBefore($addButtonContainer);
			}
			$addButtonContainer.show();
			$page.find('.option-delete-button').show();
			$divider.show();
		} else if( val.substr(0, 6) == "choose"){
			numOptions = val.substr(-1);
			for(var i = $oldOptions.length; i <= numOptions; i++){
				$.createQuestionOption().insertBefore($addButtonContainer);
			}
			$addButtonContainer.hide();
			$page.find('.option-delete-button').hide();
			$divider.show();
		}else{
			$addButtonContainer.hide();
			$divider.hide();
		}
		
		$divider
			.nextAll(".list-question-option")
				.hide()
				.find("input").attr("disabled", "true").end()
				.end()
			.nextAll(".list-question-option:lt(" + numOptions + ")")
				.find("input").removeAttr("disabled").end()
				.show();
	}
	
	$.extend({
		createQuestionOption : function(){
			return $("#list-question-option-template").clone()
					.removeAttr('id')
					.find("a:first").click(focusQuestionOption).end()
					.find('.option-delete-button').click(deleteQuestionOption).end();
				
		}
	});
	
	function addQuestionOption(){
		var $page = $("#page-add-question");
		$.createQuestionOption()
			.find("input").removeAttr("disabled").end()
			.insertBefore($page.find("#list-add-option"))
			.show();
		$page.find(".option-delete-button").show();
	};
	
	function deleteQuestionOption(){
		var $page = $("#page-add-question");
		var $visibleOptions = $page.find(".list-question-option:visible");
		
		if($visibleOptions.length <= 2){
			$page.find(".option-delete-button").hide();
		}
		
		$(this).parent("li").fadeOut(function(){
			$(this).remove();
		});
	}
	
	function focusQuestionOption(){
		$(this).find("input").focus();
	}
	
	function addQuestion(){
		var $page = $("#page-add-question");
		var title = $.trim( $page.find("#text-question-title").val() );
		var type = $page.find("#select-question-type").val();
		var typeStr = $page.find("#select-question-type option[value='"+ type +"']").text();
		var number = $(".list-question").not("#list-question-template").length;
		var $options = $page.find(".list-question-option:visible input");
		var $emptyOptions = $options.filter("[value='']");
		
		if(title == ""){
			alert("질문을 입력해 주세요.");
			$("#text-question-title").focus();
			return false;
		}
		
		switch(type){
			case "text-short":
			case "text-long":
				break;
			case "select":
				if($emptyOptions.length == $options.length){
					alert("하나 이상의 보기를 입력해 주세요.");
					$emptyOptions.first().focus();
					return false;
				}else{
					$emptyOptions.attr("disabled", "true");
				}
				break;
			default:	// 4,2,5지선다
				if($emptyOptions.length > 0){
					alert("보기를 모두 입력해 주세요.");
					$emptyOptions.first().focus();
					return false;
				}
		}
		
		var value = $page.find("form").serialize();
		
		$("#list-question-template").clone()
			.removeAttr('id')
			.find('.question-number').text((number+1) + ". ").end()
			.find('.question-title').text(title).end()
			.find('.question-type').text("유형: " + typeStr).end()
			.find('input').val(value).removeAttr('disabled').end()
			.find('.question-delete-button').click(deleteQuestion).end()
			.insertAfter('.list-question:last')
			.show();
		
		$page.dialog("close");
	}
	
	function deleteQuestion(){
		// 이함수는 $(this)가 전부 다름
		$(this).parent("li").fadeOut(function(){
			$(this).remove();
			$(".list-question:visible").each(function(idx){
				$(this).find(".question-number").text((idx+1) + ". ");
			});
		});
	}
})();